//
//  MyInfoViewController.m
//  RSW.IOS
//
//  Created by zhaiqiuqiu on 16/12/3.
//  Copyright © 2016年 com.xtion.crm. All rights reserved.
//

#import "MyInfoViewController.h"
#import "HeadImageView.h"

NSString const *MyInfoViewControllerTitleParamKey = @"MyInfoViewControllerTitleParamKey";

@interface MyInfoViewController ()<UITableViewDataSource,HeadImageViewDelegate,XUIButtonDelegate,UIImagePickerControllerDelegate,UINavigationControllerDelegate,UITextFieldDelegate>
{
    XUIButton *_modifyBtn;
    HeadImageView *_headImageView;
    XMSQueueDictionary *_qdData;
    RSWDataOperation *_manager;
    
    UITextField *_userNameTextView;
    UITextField *_mobilePhoneTextView;
    UITextField *_telTextView;
    UITextField *_emailTextView;
    UITextField *_qqTextView;
    
    UITextField *_textInputViewCell;
    
    MyInfo *_myInfo;
    
    NSString *_headFilePath;
    UIImage *_headImage;
}
@end

@implementation MyInfoViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    [self checkSession];
    
    NSString *title = self.param[MyInfoViewControllerTitleParamKey];
    [self setBackNavigateItemTitle:title];
    
    self.view.backgroundColor = [UIColor colorWithHex:mcrmSAASUISkinColorTextStylef1f4f7Color];
    
    [self createTableView:XUITabelViewStyleTypePlain];
    _ctable.showsVerticalScrollIndicator = NO;
    _ctable.separatorExistFollowCell = NO;
    
    _qdData = [XMSQueueDictionary new];
    _headImage = [UIImage new];
    _headFilePath = @"";
    
    [self initData];
    
    _manager = [[RSWDataOperation alloc]initWithDataOperationManagerDelegate:self];
    [self addMainThreadObserverWithDictionarySelector:@{CurrentUserCurrentUserHeadImageUpdateNotification:
                                                            @"observerCurrentUserCurrentUserHeadImageUpdateNotification:"}];
    [self addKeyboardObserver]; 
}


-(void)viewControllerWillDealloc
{
    [super viewControllerWillDealloc];
    [self removeObserver];
    [_manager terminateRequest];
}

-(void)initData
{
    _myInfo = [[MyInfo myInfo] copy];
    [_qdData addKey:@"mine_background" value:@"mine_background"];
    
    [_qdData addKey:@"empty" value:@"empty"];
    
    [_qdData addKey:@"移动电话" value:@"移动电话"];
    [_qdData addKey:@"联系电话" value:@"联系电话"];
    [_qdData addKey:@"Email" value:@"Email"];
    [_qdData addKey:@"QQ" value:@"QQ"];
    
    [_qdData addKey:@"change" value:@"修改"];
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

#pragma mark --
#pragma mark -- UITableView delegate
-(NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    return _qdData.count;
}

-(CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
    NSString *key = [_qdData getKeyForIndex:indexPath.row];
    if([key isEqualToString:@"empty"])
        return 10;
    else if([key isEqualToString:@"mine_background"])
        return 100 + 44;
    else if([key isEqualToString:@"change"])
    {
        return self.view.height - 100 - 44 - 10 - 54*4 - 64;
    }
    
    return 54;
}

-(UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    XMSKvPair *pair = [_qdData kvPairAtIndex:indexPath.row];
    
    CGFloat height = [self tableView:tableView heightForRowAtIndexPath:indexPath];
    
    XUITableViewCell *cell = [[XUITableViewCell alloc] initWithReuseIdentifier:@""];
//    cell.backgroundColor = [UIColor whiteColor];
//    cell.contentView.backgroundColor = [UIColor clearColor];
    
    if ([pair.idKey isEqualToString:@"mine_background"])
    {
        cell.selectionStyle = UITableViewCellSelectionStyleNone;
        
        UIImage *dataBackg = [UIImage imageNamed:pair.idKey];
        UIImageView *backgroundView = [[UIImageView alloc]initWithImage:dataBackg]; 
        backgroundView.frame = CGRectMake(0, 0, tableView.width, dataBackg.size.height);
        [cell.contentView addSubview:backgroundView];
        
        _headImageView = [[HeadImageView alloc]initWithFrame:CGRectMake(13, 0, 90, 90) userInteractionEnabled:YES];
        _headImageView.delegate = self;
        _headImageView.headImage = [CCurrentUser currentUserHeadImage];
        _headImageView.layer.cornerRadius = 45;
        _headImageView.layer.masksToBounds = YES;
        //_headImageView.layer.borderWidth = 1.5;
        //_headImageView.layer.borderColor = [[UIColor whiteColor] CGColor];
        _headImageView.tag = 10000;
        _headImageView.centerX = self.view.frame.size.width/2;
        _headImageView.centerY = 50;
        
        [backgroundView addSubview:_headImageView];
        
        _userNameTextView = [[UITextField alloc]initWithFrame:CGRectMake(0, 0, 100, 44)];
        _userNameTextView.textAlignment = NSTextAlignmentCenter;
        _userNameTextView.font = [UIFont systemFontOfSize:15];
        _userNameTextView.backgroundColor = [UIColor clearColor];
        _userNameTextView.textColor = [UIColor whiteColor];
        _userNameTextView.returnKeyType = UIReturnKeyDone;
        _userNameTextView.text = _myInfo.userName;
        _userNameTextView.top = _headImageView.bottom;
        _userNameTextView.centerX = self.view.frame.size.width/2;
        
        _userNameTextView.delegate = self;
        
        [cell.contentView addSubview:_userNameTextView];
        
        cell.backgroundColor = [UIColor colorWithHex:mcrmSAASUIShinColorTextStyle2196F3Color];
    }
    else if([pair.idKey isEqualToString:@"empty"])
    {
        cell.backgroundColor = _ctable.backgroundColor;
        cell.selectionStyle = UITableViewCellSelectionStyleNone;
    }
    else if([pair.idKey isEqualToString:@"change"])
    {
        cell.hiddenFollowSeparateLine = YES;
        cell.backgroundColor = [UIColor whiteColor];
        cell.selectionStyle = UITableViewCellSelectionStyleNone;
        
        CGFloat bottom = height -13;
       
        _modifyBtn = [XUIButton buttonWithStyleType:XUIButtonStyleTypeCustom delegate:self];
        _modifyBtn.frame = CGRectMake(13, 0, tableView.width - 13 - 13, 44);
        _modifyBtn.bottom = bottom;
        _modifyBtn.backgroundColor = [UIColor colorWithHex:mcrmSAASUIShinColorTextStyle2196F3Color];
        _modifyBtn.layer.cornerRadius = 2;
        _modifyBtn.layer.masksToBounds = YES;
        [_modifyBtn SetTitleColor:[UIColor whiteColor]];
        [_modifyBtn SetFont:[UIFont systemFontOfSize:18]];
        [_modifyBtn SetTitle:@"修改"];
        
        [cell.contentView addSubview:_modifyBtn];
    }
    else if([pair.idKey isEqualToString:@"移动电话"])
    {
        cell.selectionStyle = UITableViewCellSelectionStyleNone;
        cell.szTag = pair.idKey;
        
        UILabel *label = [[UILabel alloc]initWithFrame:CGRectMake(13, 0, 80, height)];
        label.textAlignment = NSTextAlignmentLeft;
        label.font = [UIFont systemFontOfSize:15];
        label.textColor = [UIColor colorWithHex:0x9b9b9b];
        [cell.contentView addSubview:label];
        label.text = pair.idValue;
        [cell.contentView addSubview:label];
        
        _mobilePhoneTextView = [[UITextField alloc]initWithFrame:CGRectMake(label.right+5, 0, tableView.width-label.right-5-13, height)];
        _mobilePhoneTextView.textAlignment = NSTextAlignmentLeft;
        _mobilePhoneTextView.font = [UIFont systemFontOfSize:15];
        _mobilePhoneTextView.textColor = [UIColor colorWithHex:0x333333];
        _mobilePhoneTextView.returnKeyType = UIReturnKeyDone;
        _mobilePhoneTextView.text = _myInfo.mobilePhone;
        
        _mobilePhoneTextView.delegate = self;
        
        [cell.contentView addSubview:_mobilePhoneTextView];
    }
    else if([pair.idKey isEqualToString:@"联系电话"])
    {
        cell.selectionStyle = UITableViewCellSelectionStyleNone;
        cell.szTag = pair.idKey;
        
        UILabel *label = [[UILabel alloc]initWithFrame:CGRectMake(13, 0, 80, height)];
        label.textAlignment = NSTextAlignmentLeft;
        label.font = [UIFont systemFontOfSize:15];
        label.textColor = [UIColor colorWithHex:0x9b9b9b];
        [cell.contentView addSubview:label];
        label.text = pair.idValue;
        [cell.contentView addSubview:label];
        
        _telTextView = [[UITextField alloc]initWithFrame:CGRectMake(label.right+5, 0, tableView.width-label.right-5-13, height)];
        _telTextView.textAlignment = NSTextAlignmentLeft;
        _telTextView.font = [UIFont systemFontOfSize:15];
        _telTextView.textColor = [UIColor colorWithHex:0x333333];
        _telTextView.returnKeyType = UIReturnKeyDone;
        _telTextView.text = _myInfo.tel;
        
        _telTextView.delegate = self;
        
        [cell.contentView addSubview:_telTextView];
        
    }
    else if([pair.idKey isEqualToString:@"Email"])
    {
        cell.selectionStyle = UITableViewCellSelectionStyleNone;
        cell.szTag = pair.idKey;
        
        UILabel *label = [[UILabel alloc]initWithFrame:CGRectMake(13, 0, 80, height)];
        label.textAlignment = NSTextAlignmentLeft;
        label.font = [UIFont systemFontOfSize:15];
        label.textColor = [UIColor colorWithHex:0x9b9b9b];
        [cell.contentView addSubview:label];
        label.text = pair.idValue;
        [cell.contentView addSubview:label];
        
        _emailTextView = [[UITextField alloc]initWithFrame:CGRectMake(label.right+5, 0, tableView.width-label.right-5-13, height)];
        _emailTextView.textAlignment = NSTextAlignmentLeft;
        _emailTextView.font = [UIFont systemFontOfSize:15];
        _emailTextView.textColor = [UIColor colorWithHex:0x333333];
        _emailTextView.returnKeyType = UIReturnKeyDone;
        _emailTextView.text = _myInfo.email;
        
        _emailTextView.delegate = self;
        
        [cell.contentView addSubview:_emailTextView];
        
    }
    else if([pair.idKey isEqualToString:@"QQ"])
    {
        cell.selectionStyle = UITableViewCellSelectionStyleNone;
        cell.szTag = pair.idKey;
        
        UILabel *label = [[UILabel alloc]initWithFrame:CGRectMake(13, 0, 80, height)];
        label.textAlignment = NSTextAlignmentLeft;
        label.font = [UIFont systemFontOfSize:15];
        label.textColor = [UIColor colorWithHex:0x9b9b9b];
        [cell.contentView addSubview:label];
        label.text = pair.idValue;
        [cell.contentView addSubview:label];
        
        _qqTextView = [[UITextField alloc]initWithFrame:CGRectMake(label.right+5, 0, tableView.width-label.right-5-13, height)];
        _qqTextView.textAlignment = NSTextAlignmentLeft;
        _qqTextView.font = [UIFont systemFontOfSize:15];
        _qqTextView.textColor = [UIColor colorWithHex:0x333333];
        _qqTextView.returnKeyType = UIReturnKeyDone;
        _qqTextView.text = _myInfo.qq;
        
        _qqTextView.delegate = self;
        
        [cell.contentView addSubview:_qqTextView];
    }
    
    return cell;
}

-(UIEdgeInsets)tableView:(XUITableView *)tableView setSeparatorInsetForRowAtIndexPath:(NSIndexPath *)indexPath
{
    NSString *key = [_qdData getKeyForIndex:indexPath.row];
    
    if([key isEqualToString:@"empty"] || [key isEqualToString:@"mine_background"] || [key isEqualToString:@"QQ"])
        return UIEdgeInsetsZero;
    
    if(indexPath.row == _qdData.count - 1)
        return UIEdgeInsetsMake(0, 0, 0, 0);
    
    if([[_qdData getKeyForIndex:indexPath.row + 1] isEqualToString:@"empty"] )
        return UIEdgeInsetsMake(0, 0, 0, 0);
    
    
    return UIEdgeInsetsMake(0, 13, 0, 0);
}

-(void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    [tableView deselectRowAtIndexPath:indexPath animated:YES];
    
    NSString *key = [_qdData getKeyForIndex:indexPath.row];
    if([key isEqualToString:@"mine_background"])
    {
        [self choicePhoto];
    }
}

#pragma mark --
#pragma mark -- Photo
-(void)choicePhoto
{
    [UIViewController closeKeyBoard];
    
    if ([XMSFileHelper getSystemFreeSize] / 1024 / 1024 < 150)
    {
        [UIAlertView showInfoMsg:@"存储空间不足，未能获取图片"];
        return;
    }
    
    [XUIActionSheetView actionSheetViewWithTitle:@"t" cancelButtonTitle:@"取消" otherButtonTitles:@[@"拍照",@"从相册选择"] show:^(NSUInteger clickIndex)
     {
         //if ([UIImagePickerController isCameraDeviceAvailable:UIImagePickerControllerCameraDeviceRear])
         {
             UIImagePickerController *controller = [UIImagePickerController new];
             controller.delegate = self;
             controller.sourceType = clickIndex == 0 ? UIImagePickerControllerSourceTypeCamera : UIImagePickerControllerSourceTypePhotoLibrary;
             controller.allowsEditing = YES;
             
             [UIViewController presentViewController:controller animated:YES completion:^
              {}];
         }
     }];
}

- (void)imageOperation:(UIImage *)newImage
{
    DispatchGlobalThreadAsync(^
                              {
                                  [self beginProgressViewPanel:@"图片处理中"];
                                  
                                  NSString *guid = [XMSGUID GUIDLowString];
                                  NSString *filename = [NSString stringWithFormat:@"%@.jpg", guid];
                                  NSString *path = [[XMSFileHelper tempPath] stringByAppendingPathComponent:filename];
                                  _headFilePath = path;
                                  
                                  [UIImageJPEGRepresentation(newImage, 1) writeToFile:path atomically:NO];
                                  [UIImage imageFileSize:[XMSFileHelper getFileSize:path] imageSize:newImage.size compressParam:^(CGFloat zoomMultiple,CGSize zoomSize,CGFloat quality)
                                   {
                                       CGSize size = zoomSize;
                                       UIImage *image = [UIImage imageFromImage:newImage scaledToSize:size];
                                       _headImage = image;
                                       
                                       //保存原始照片到本地
                                       NSData *data = UIImageJPEGRepresentation(image, quality);
                                       [data writeToFile:path atomically:NO];
                                   }];
                                  
                                  if(_manager == nil)
                                      _manager = [[RSWDataOperation alloc] initWithDataOperationManagerDelegate:self];
                                  
                                  [self setProgressViewPanelReleaseDelayTime:1];
                                  
                                  NSArray *fileIdArray = [_manager uploadImage:@[path] paras:nil];
                                  if(fileIdArray.count > 0)
                                  {
                                      _myInfo.logoURL = fileIdArray[0];
                                      
                                      _headImageView.headImage = _headImage;
                                  }
                                  
                                  [self endProgressViewPanel];
                              });
}

- (void)imagePickerController:(UIImagePickerController *)picker didFinishPickingImage:(UIImage *)image editingInfo:(NSDictionary *)editingInfo
{
    [self imageOperation:image];
    
    [UIViewController dismissViewControllerAnimated:YES completion:^
     {
     }];
}

- (void)imagePickerControllerDidCancel:(UIImagePickerController *)picker
{
    [UIViewController dismissViewControllerAnimated:YES completion:^
     {
     }];
}

#pragma mark --
#pragma mark -- submit
-(BOOL)submit
{
    if(_userNameTextView.text.length <= 0)
    {
        [UIAlertView showInfoMsg:@"姓名不能为空"];
        return NO;
    }
    
    return YES;
}
-(void)clickedUpInsideOfButton:(XUIButton *)btn
{
    if([self submit] == NO)
        return;
    
    if(btn == _modifyBtn)
    {
        [XUIAlertView alertViewWithTitle:@"提示" message:@"是否保存该信息" cancelButtonTitle:@"保存" otherButtonTitles:@[@"取消"] clickBlock:^(NSInteger nClickindex)
         {
             if(nClickindex == 0)
             {
                 [self modifyRecord];
             }
         }];
    }
}

- (void)modifyRecord
{
    _myInfo.userName = _userNameTextView.text;
    _myInfo.mobilePhone = _mobilePhoneTextView.text;
    _myInfo.tel = _telTextView.text;
    _myInfo.email = _emailTextView.text;
    _myInfo.qq = _qqTextView.text;
    
    [_manager modifyMyinfoByInfo:_myInfo headFilePath:_headFilePath completion:^(NSInteger nResult, BOOL bResult, NSError *error)
     {
         switch(nResult)
         {
             case YES:
             {
                 if(bResult == YES)
                 {
                     [XUIAlertView alertViewWithTitle:@"提示" message:@"修改成功" cancelButtonTitle:@"确定" otherButtonTitles:nil clickBlock:^(NSInteger nClickindex)
                      {
                          [XUINavigationController pop];
                      }];
                 }
                 else
                 {
                     [UIAlertView showErrorMsg:@"修改失败"];
                 }
                 break;
             }
             default:
             {
                 [UIAlertView showErrorMsg:@"修改失败"];
                 break;
             }
         }
     }];
}


-(void)clickHeadImageView:(HeadImageView *)headImageView
{
    [[[ImageBrowserViewController alloc]initWithImages:@[headImageView.headImage]] zoomPresentPreviewImageViewController:@[headImageView]];
}

#pragma mark --
#pragma mark -- keyBoard
- (BOOL)keyboardDidShow:(NSNotification *)noti
{
    BOOL bResult = [super keyboardDidShow:noti];
    if (YES == bResult)
    {
        _ctable.height -= self.keyboardOffSet;
        
        if (_textInputViewCell != nil)
        {
            [_ctable scrollRectToVisible:_textInputViewCell.frame animated:YES];
        }
    }
    return bResult;
}

-(BOOL)keyboardWillHide:(NSNotification *)noti
{
    BOOL bResult = [super keyboardWillHide:noti];
    if(YES == bResult)
    {
        _ctable.height += self.keyboardOffSet;
    }
    return bResult;
}

-(void)keyboardWillChangeSize:(CGFloat)changeSize withAnimationDuration:(CGFloat)duration curve:(UIViewAnimationCurve)curve
{
    _ctable.height += changeSize;
}

#pragma mark --
#pragma mark -- UITextFieldDelegate
-(BOOL)textFieldShouldReturn:(UITextField *)textField
{
    [textField resignFirstResponder];
    
    return YES;
}

- (BOOL)textFieldShouldBeginEditing:(UITextField *)textField
{
    _textInputViewCell = textField;
    return YES;
}

- (void)textFieldDidEndEditing:(UITextField *)textField
{
    _textInputViewCell = nil;
}

#pragma mark --
#pragma mark -- observer
-(void)observerCurrentUserCurrentUserHeadImageUpdateNotification:(NSNotification*)noti
{
    XUITableViewCell *cell = (XUITableViewCell *)[_ctable cellForRowAtIndexPath:[NSIndexPath indexPathForRow:0 inSection:0]];
    if(cell != nil)
    {
        _headImageView.headImage = [CCurrentUser currentUserHeadImage];
    }
}

@end
